import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { walletApi } from '../../services/apiService';

const WalletHome = () => {
  const [stats, setStats] = useState({
    dids: [],
    credentials: [],
    loading: true,
    error: null
  });

  // 加载数据
  useEffect(() => {
    const fetchData = async () => {
      try {
        // 同时请求DID和凭证数据
        const [didsResponse, credentialsResponse] = await Promise.all([
          walletApi.listDids(),
          walletApi.listCredentials()
        ]);

        setStats({
          dids: didsResponse.success ? didsResponse.dids : [],
          credentials: credentialsResponse.success ? credentialsResponse.credentials : [],
          loading: false,
          error: null
        });
      } catch (error) {
        console.error('获取钱包数据失败:', error);
        setStats(prev => ({
          ...prev,
          loading: false,
          error: '获取数据时出错，请稍后再试。'
        }));
      }
    };

    fetchData();
  }, []);

  // 计算凭证状态
  const calculateCredentialStats = () => {
    const now = new Date();
    let active = 0;
    let expired = 0;
    let revoked = 0;

    stats.credentials.forEach(cred => {
      if (cred.revoked) {
        revoked++;
      } else if (cred.expirationDate && new Date(cred.expirationDate) < now) {
        expired++;
      } else {
        active++;
      }
    });

    return { active, expired, revoked };
  };

  const credentialStats = calculateCredentialStats();

  if (stats.loading) {
    return (
      <div className="loading-spinner">
        <div className="spinner-border text-primary" role="status">
          <span className="visually-hidden">加载中...</span>
        </div>
      </div>
    );
  }

  return (
    <div className="wallet-home">
      <div className="card mb-4">
        <div className="card-body">
          <h4 className="card-title mb-4">钱包概览</h4>
          
          {stats.error && (
            <div className="alert alert-danger">{stats.error}</div>
          )}
          
          <div className="row g-4">
            <div className="col-md-6">
              <div className="card h-100">
                <div className="card-body">
                  <h5 className="card-title">
                    <i className="bi bi-person-badge me-2"></i>
                    数字身份
                  </h5>
                  <p className="card-text fs-4">{stats.dids.length} 个身份</p>
                  
                  {stats.dids.length > 0 ? (
                    <div className="list-group mt-3">
                      {stats.dids.slice(0, 2).map((did, index) => (
                        <div key={index} className="list-group-item list-group-item-action d-flex justify-content-between align-items-center">
                          <div className="text-truncate" style={{ maxWidth: '80%' }}>
                            <small className="d-block text-muted">方法: {did.method}</small>
                            <small className="d-block text-truncate">{did.id}</small>
                          </div>
                          <span className="badge bg-primary rounded-pill">
                            {new Date(did.created).toLocaleDateString()}
                          </span>
                        </div>
                      ))}
                    </div>
                  ) : (
                    <div className="alert alert-warning mt-3">
                      您还没有创建数字身份。
                      <Link to="/wallet/dids/create" className="alert-link ms-2">
                        立即创建
                      </Link>
                    </div>
                  )}
                  
                  <div className="mt-3">
                    <Link to="/wallet/dids" className="btn btn-outline-primary btn-sm">
                      查看所有身份
                    </Link>
                  </div>
                </div>
              </div>
            </div>
            
            <div className="col-md-6">
              <div className="card h-100">
                <div className="card-body">
                  <h5 className="card-title">
                    <i className="bi bi-card-list me-2"></i>
                    凭证统计
                  </h5>
                  <p className="card-text fs-4">{stats.credentials.length} 个凭证</p>
                  
                  <div className="mt-3">
                    <div className="row g-2 text-center">
                      <div className="col-4">
                        <div className="p-3 border rounded bg-light">
                          <div className="status-badge active d-inline-block mb-2">有效</div>
                          <h5 className="mb-0">{credentialStats.active}</h5>
                        </div>
                      </div>
                      <div className="col-4">
                        <div className="p-3 border rounded bg-light">
                          <div className="status-badge expired d-inline-block mb-2">过期</div>
                          <h5 className="mb-0">{credentialStats.expired}</h5>
                        </div>
                      </div>
                      <div className="col-4">
                        <div className="p-3 border rounded bg-light">
                          <div className="status-badge revoked d-inline-block mb-2">撤销</div>
                          <h5 className="mb-0">{credentialStats.revoked}</h5>
                        </div>
                      </div>
                    </div>
                  </div>
                  
                  <div className="mt-3">
                    <Link to="/wallet/credentials" className="btn btn-outline-primary btn-sm">
                      管理凭证
                    </Link>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <div className="card">
        <div className="card-body">
          <h4 className="card-title mb-4">最近活动</h4>
          
          <div className="alert alert-info">
            <i className="bi bi-info-circle me-2"></i>
            欢迎使用EduVerse钱包应用！通过左侧菜单管理您的身份和凭证。
          </div>
          
          <div className="d-grid gap-2 d-md-flex justify-content-md-center mt-4">
            <Link to="/wallet/dids/create" className="btn btn-primary">
              <i className="bi bi-plus-circle me-2"></i>
              创建数字身份
            </Link>
            <Link to="/wallet/credentials/import" className="btn btn-outline-primary">
              <i className="bi bi-download me-2"></i>
              导入凭证
            </Link>
            <Link to="/wallet/proofs" className="btn btn-outline-primary">
              <i className="bi bi-shield-check me-2"></i>
              生成证明
            </Link>
          </div>
        </div>
      </div>
    </div>
  );
};

export default WalletHome; 